package br.com.tenax.dao;

import java.util.ArrayList;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import br.com.tenax.fornedor.Fornecedor;

public class FornecedorDAOHibernate implements FornecedorDAO {

	protected Session session = HibernateUtil.getSessionFactory().openSession();

	public Session getSession() {
		return HibernateUtil.getSession();
	}

	public void incluir(Fornecedor fornecedor) {
		try {
			session = getSession();
			session.beginTransaction();
			session.save(fornecedor);
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	@Override
	public void atualizar(Fornecedor fornecedor) {
		try {
			session = getSession();
			session.beginTransaction();
			session.merge(fornecedor);
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}

	}

	@Override
	public void deletar(Fornecedor fornecedor) {
		try {
			session = getSession();
			session.beginTransaction();
			session.delete(fornecedor);
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	@Override
	public Fornecedor consultar(Fornecedor fornecedor) {
		Fornecedor f = new Fornecedor();
		try {
			session = getSession();
			session.beginTransaction();
			f = (Fornecedor) session.get(Fornecedor.class, fornecedor.getId());
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}

		return f;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Fornecedor> listar() {
		
		List<Fornecedor> lista = new ArrayList<>();
		try {
			session = getSession();
			session.beginTransaction();
			Query query = session.createQuery("from Fornecedor");
			lista = (List<Fornecedor>) query.list();
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return lista;
	}
}